import axios from 'axios';
import isEqual from 'lodash/isEqual';
import memoize from "memoize-one";
import { formatMessage } from 'umi/locale';

function formatter(data, parentName) {
  return data
    .map(item => {
      if (!item.name || !item.path) {
        return null;
      }
      let locale = 'menu';
      if (parentName) {
        locale = `${parentName}.${item.name}`;
      } else {
        locale = `menu.${item.name}`;
      }

      const result = {
        ...item,
        name: formatMessage({ id: locale, defaultMessage: item.name }),
        locale
      };
      if (item.routes) {
        const children = formatter(item.routes,locale);
        // Reduce memory usage
        result.children = children;
      }
      delete result.routes;
      return result;
    })
    .filter(item => item);
}

const memoizeFormatter = memoize(formatter, isEqual);

const filterMenuData = menuData => {
  if (!menuData) {
    return [];
  }
  return menuData
    .filter(item => item.name && !item.hideInMenu)
    .map(item => getSubMenu(item))
    .filter(item => item);
};

const getSubMenu = item => {
  if (item.children && !item.hideChildrenInMenu && item.children.some(child => child.name)) {
    return {
      ...item,
      children: filterMenuData(item.children), // eslint-disable-line
    };
  }
  return item;
};


const getBreadcrumbNameMap = menuData => {
  const routerMap = {};

  const flattenMenuData = data => {
    data.forEach(menuItem => {
      if (menuItem.children) {
        flattenMenuData(menuItem.children);
      }
      routerMap[menuItem.path] = menuItem;
    });
  };
  flattenMenuData(menuData);
  return routerMap;
};

const memoizeGetBreadcrumbNameMap = memoize(getBreadcrumbNameMap, isEqual);

export default {
  namespace: 'menu',
  state: {
    menuData: [],
    breadcrumbNameMap: {},
  },

  effects: {
    *getMenuData ({ }, { put, call }) {
      const res = yield call(axios.get, "/api/admin/menu-list");
      const menuData = filterMenuData(memoizeFormatter(res.data.data));
      const breadcrumbNameMap = memoizeGetBreadcrumbNameMap(menuData);
      yield put({
        type: 'save',
        payload: { menuData, breadcrumbNameMap },
      });
    },
  },

  reducers: {
    save (state, action) {
      return {
        ...state,
        ...action.payload,
      };
    }
  },

  subscriptions: {
    setup ({ history }) {

    },
  },
};
